<template>
    <div class="studentList pl10 pr10">
        <div class="flex-row-sb" style="width: 100%">
            <div style="width: 20%">
                <SelectClassTree ref="selectClassTree" @filterDataByClass="filterDataByClass" :schoolId="searchForm.schoolId"></SelectClassTree>
            </div>
            <div style="width: 80%" v-show="isShowTable">
                <avue-crud
                    :table-loading="loading"
                    ref="crud"
                    :option="option"
                    :search.sync="searchForm"
                    :page.sync="page"
                    :data="data"
                    @on-load="onLoad"
                    @search-change="handleSearchChange"
                    @row-del="handleRowDel"
                    @row-update="handleRowUpdate"
                    @error="error"
                >
                    <template slot="menuLeft" slot-scope="{ size }">
                        <el-button v-if="isExport" icon="el-icon-bottom" type="primary" size="mini" @click="handleExportExcel">导出Excel</el-button>
                        <sc-pop-button v-if="isSync" type="primary" size="mini" title="是否同步数据？" @ok="updateDataSynchronize">
                            同步数据
                        </sc-pop-button>

                        <el-button v-if="isImport" size="mini" icon="el-icon-top" type="primary" @click="importStudentNumber">导入学生信息</el-button>
                        <el-button v-if="isHikAuthor" size="mini" icon="el-icon-top" type="danger" @click="authorizationStudent">
                            海康授权学生
                        </el-button>
                        <el-button v-if="isSendNotice" type="primary" size="mini" @click="handleSendNotice()">发送通知</el-button>

                        <el-button v-if="isAddParents" type="primary" size="mini" @click="handleAddParent()">添加家长</el-button>
                    </template>

                    <!-- 自定义列 -->
                    <template slot="human_face" slot-scope="scope">
                        <div class="media">
                            <img
                                :src="scope.row.human_face"
                                style="width: 50px; border-radius: 3px"
                                v-if="scope.row.human_face"
                                @click="$imgView([scope.row.human_face])"
                            />
                            <el-link type="warning" v-else @click="popup.getFaceFrom = true">去采集</el-link>
                        </div>
                    </template>

                    <!-- 学生图片 -->
                    <template slot-scope="{ row }" slot="avatar">
                        <el-popover v-if="row.avatar" placement="right-start" width="400" trigger="hover">
                            <img style="width: 100%" :src="row.avatar"/>
                            <el-image slot="reference" style="height: 40px" :src="row.avatar" fit="fill" :preview-src-list="[row.avatar]"></el-image>
                        </el-popover>
                        <el-tag type="info">暂无头像</el-tag>
                    </template>

                    <template slot-scope="{ row }" slot="isSendAccessMessage">
                        <el-switch v-model="row.isSendAccessMessage" @change="handlePutSendAccessMessage(row)"></el-switch>
                    </template>

                    <!--自定义表单-->
                    <template slot-scope="{ value, type }" slot="human_faceForm">
                        <img v-if="value && type === 'view'" style="width: 200px" :src="value" @click="$imgView([value])"/>
                        <el-tag v-else type="info" size="mini">未采集</el-tag>
                    </template>
                    <template slot-scope="{ value }" slot="isSendAccessMessageForm">
                        <el-tag :type="value ? '' : 'danger'">{{ value ? '发送' : '不发送' }}</el-tag>
                    </template>

                    <!--自定义操作栏-->
                    <template slot-scope="{ row }" slot="menu">
                        <el-button v-if="isRestore && row.externalId == '' && !row.levelDelete" type="text" style="color: red" size="mini"
                                   @click="handleRestore(row)">恢复
                        </el-button>
                        <el-button v-if="isDel && row.studentNo === '' && row.externalId == ''" type="text" size="mini" @click="handleRowDel(row)">删除
                        </el-button>
                        <el-button v-if="isEdit" type="text" size="mini" @click="handleEdit(row)">编辑</el-button>
                        <el-button v-if="isParent" type="text" size="mini" @click="handleViewParents(row)">家长列表</el-button>
                        <el-button v-if="isSendNotice && row.externalId != ''" type="text" size="mini" @click="handleSendCurrentNotice(row)">发送通知</el-button>
                        <sc-popButton v-if="row.externalId != ''" type="text" size="mini" title="确认同步吗?" @ok="handleInfoSync(row.schoolId, row.id)">
                            同步
                        </sc-popButton>
                        <!-- <el-button
                            type="text"
                            size="mini"
                            @click="
                                popup.studentInfoPopup = true
                                currentRow = row
                            "
                        >
                            企微学生信息
                        </el-button>
                        <sc-popButton type="text" size="mini" title="确认同步吗?" @ok="handleQyDataSync(row.schoolId, row.id)">
                            同步企微家长信息
                        </sc-popButton> -->
                    </template>
                </avue-crud>
            </div>

            <div style="width: 80%" v-show="isShowParent">
                <el-card class="addParentForm" style="margin-bottom: 10px; height: 100%;">
                    <el-form :model="form" label-width="80px" :rules="rules" ref="ruleForm">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="form.name" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="学号" prop="number" required>
                            <el-input v-model="form.number" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="身份证" prop="id">
                            <el-input v-model="form.id" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="内外宿" prop="type" required>
                            <el-radio-group v-model="form.type">
                                <el-radio :label="0">内宿</el-radio>
                                <el-radio :label="1">外宿</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="班级" required>
                            <div style="margin-bottom:5px;width: 400px;" v-if="classList.length">
                                <el-tag v-for="tag in classList" :key="tag.id" closable @close="handleClose(tag)" @click="handleSelectOtherClass">
                                    {{ tag.nick }}
                                </el-tag>
                            </div>
                            <el-button v-else type="text" @click="handleAddClass">添加</el-button>
                        </el-form-item>

                        <el-form-item label="家长">
                            <div class="item-box" v-for="(item,index) in form.parents" :key="index">
                                <el-input placeholder="填写家长手机号" maxlength="11" v-model="item.parent" class="input-with-select" style="width:300px;">
                                    <el-select default-first-option v-model="item.select" slot="prepend" placeholder="请选择">
                                        <el-option :label="item.name" :value="item.value" v-for="(item,index) in parents" :key="index"></el-option>
                                    </el-select>
                                </el-input>
                                <i style="color:red;margin-left: 10px" class="el-icon-close" @click="handleDelLine(item)" v-if="index!=0"></i>
                            </div>
                            <el-button type="text" @click="form.parents.push([])">添加家长</el-button>
                        </el-form-item>
                    </el-form>
                    <el-button
                        type="primary"
                        style="width: 100px; margin-left: 80px"
                        plain
                        size="mini"
                        @click="handleSaveAdmin('ruleForm')"
                    >
                        保 存
                    </el-button>
                    <el-button
                        type="info"
                        style="width: 100px; margin-left: 15px;margin-bottom: 15px"
                        plain
                        size="mini"
                        @click="handleCancel"
                    >
                        取 消
                    </el-button>

                </el-card>
            </div>
        </div>

        <!-- 组件 -->
        <GetFaceFromPopup
            :face-img="faceImg"
            @clearFaceImg="faceImg = ''"
            v-model="popup.getFaceFrom"
            @openFacePopup="popup.getFace = true"
        ></GetFaceFromPopup>
        <!-- 采集人脸中-->
        <GetFacePopup @getFaceImg="getFaceImg" v-model="popup.getFace"></GetFacePopup>

        <!-- 家长列表-->
        <ParentListPopup v-model="popup.parentListPopup" :rowData="currentRow"></ParentListPopup>
        <!-- qy学生信息-->
        <StudentInfoPopup v-model="popup.studentInfoPopup" :rowData="currentRow"></StudentInfoPopup>

        <!-- 学号导入 -->
        <UploadExcelPopup v-model="popup.studentBatchPopup" @success="upLoadSuccess" :currentData="currentTreeNodeData"></UploadExcelPopup>

        <!-- 学号授权 -->
        <AuthorizationStudent
            v-model="popup.authorizationStudentPopup"
            @success="upLoadSuccess"
            :currentData="currentTreeNodeData"
        ></AuthorizationStudent>

        <!-- 发送通知 -->
        <SendNotice v-model="popup.sendNotice" :studentData="studentData" :schoolId="searchForm.schoolId"></SendNotice>

        <RightsProfile @filterClass="filterClass" v-model="popup.selectClass" :schoolId="searchForm.schoolId"></RightsProfile>

        <el-dialog :title="dialogTitle" :visible.sync="showErrorData" width="30vw">
            <ul style="padding: 30px">
                <li v-for="(item, index) in errorData" :key="index" style="margin-bottom: 15px">{{ item }}</li>
            </ul>
            <div slot="footer">
                <el-button @click="showErrorData = false">关 闭</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import GetFacePopup from './components/getFacePopup' //采集人脸中
import GetFaceFromPopup from './components/getFaceFromPopup' //抓取人脸
import StudentInfoPopup from './components/studentInfoPopup'
import ParentListPopup from './components/parentListPopup'
import SelectClassTree from 'admin/smartCampus/components/selectClassTree'
import UploadExcelPopup from './components/uploadExcelPopup.vue'
import AuthorizationStudent from './components/authorizationStudent.vue'
import SendNotice from './components/sendNotice.vue'
import RightsProfile from './components/rightsProfile'
import page from 'admin/mixins/page'
import {dataSynchronize, studentInfoSync} from "admin/api/schoolConfig/studentList";

const parents = [
    {
        name: '爷爷',
        value: 0,
    }, {
        name: '奶奶',
        value: 1,
    },
    {
        name: '爸爸',
        value: 2,
    },
    {
        name: '妈妈',
        value: 3,
    },

]
export default {
    mixins: [page],
    name: 'studentList',
    components: {
        GetFaceFromPopup,
        StudentInfoPopup,
        ParentListPopup,
        GetFacePopup,
        SelectClassTree,
        UploadExcelPopup,
        AuthorizationStudent,
        SendNotice,
        RightsProfile
    },
    data() {
        return {
            isShowTable: true,
            isShowParent: false,
            currentRow: {}, //当前选中行数据
            searchForm: {
                schoolId: this.$store.state.team.currTeam.id,
            },
            data: [],
            urls: {
                0: 'schoolConfig',
                1: 'studentList',
                2: 'getStudentList',
            },
            faceImg: '', //人脸头像
            popup: {
                studentInfoPopup: false,
                parentListPopup: false,
                getFaceFrom: false, //设置人脸表单
                getFace: false,
                studentBatchPopup: false, //学号导入
                authorizationStudentPopup: false, //学生授权
                sendNotice: false, //学生通知
                selectClass: false   //选择班级
            },
            currentTreeNodeData: null,
            errorData: [],
            showErrorData: false,

            img_file: [], //富文本图片文件
            studentData: [],
            form: {
                type: 0,
                parents: [{
                    select: 0
                }]
            },
            rules: {
                name: [
                    {required: true, message: '请输入名称', trigger: 'blur'},
                ],
                number: [
                    {required: true, message: '请输入学号', trigger: 'blur'},
                ],
                type: [
                    {required: true, message: '请输入名称', trigger: 'blur'},
                ],
            },
            parents: parents,
            currentRow: {},
            classList: [],    //选择的班级
            dialogTitle: '错误学生名字'
        }
    },
    computed: {
        option() {
            return {
                ...window.avueCrud,
                header: this.isSync && this.isImport,
                dialogWidth: '50%',
                addTitle: '添加通知',
                labelWidth: 100,
                menuAlign: 'left',
                menuWidth: 300,
                column: [
                    {
                        hide: true,
                        label: '学校',
                        prop: 'schoolName',
                        search: true,
                        order: 1,
                        searchSpan: 5,
                        searchLabelWidth: 50,
                        type: 'select',
                        props: {
                            label: 'schoolName',
                            value: 'id',
                        },
                        searchLable: 'schoolId',
                        searchValue: this.$store.state.team.currTeam.id,
                        dicData: this.$store.state.team.teams,
                        display: false,
                        change: (param) => {
                            if (!this.isFirst) {
                                this.searchForm.levelIds = ''
                                this.searchForm.schoolId = param.value
                                this.getData(this.searchForm)
                            } else {
                                this.isFirst = false
                            }
                        },
                    },
                    {
                        label: '学生姓名',
                        prop: 'nick',
                        search: true,
                        searchSpan: 5,
                        order: 2,
                        row: true,
                        span: 24,
                        addDisplay: false,
                        html: true,
                        formatter: (row, val) => {
                            return row.externalId == '' ? `<span style="color:#f3d9a9">${val}</span>` : val
                        },
                    },
                    {
                        label: '班级',
                        prop: 'levelNick',
                        display: false,
                        width: 200,
                        addDisplay: false,
                        html: true,
                        formatter: (row, val) => {
                            return row.levelDelete ? `<span style="color:#f3d9a9">${val}</span>` : val
                        },
                    },
                    {
                        label: '学号',
                        prop: 'studentNo',
                        row: true,
                        span: 24,
                        search: true,
                        searchSpan: 5,
                        searchLabelWidth: 50,
                        formatter(row, val) {
                            return val ? val : '/'
                        },
                        addDisplay: false,
                    },

                    {
                        label: '性别',
                        prop: 'gender',
                        width: 140,
                        dicData: [
                            {
                                label: '男',
                                value: true,
                            },
                            {
                                label: '女',
                                value: false,
                            },
                        ],
                        display: false,
                    },
                    {
                        label: '学生类型',
                        prop: 'type',
                        type: 'select',
                        row: true,
                        span: 24,
                        dicData: [
                            {
                                label: '走读生',
                                value: 0,
                            },
                            {
                                label: '住校生',
                                value: 1,
                            },
                        ],
                        html: true,
                        formatter(row, val) {
                            return val === 0 ? '<span style="color:green">走读生</span>' : '<span style="color:red">住校生</span>'
                        },
                        display: false,
                    },
                    {
                        label: '身份证',
                        prop: 'idCard',
                        row: true,
                        span: 24,
                        formatter(row, val) {
                            return val ? val : '/'
                        },
                        addDisplay: false,
                    },
                    {
                        label: '学生图片',
                        prop: 'avatar',
                        display: false,
                        width: 100,
                    },
                    {
                        label: '通知内容',
                        prop: 'itemContent',
                        row: true,
                        width: 300,
                        align: 'left',
                        span: 24,
                        hide: true,
                        editDisplay: false,
                    },
                    {
                        label: '更新时间',
                        prop: 'updateTime',
                        width: 140,
                        display: false,
                    },
                ],
            }
        },
    },

    methods: {
        // 获取学校树
        filterDataByClass(obj) {
            this.currentRow = obj
            this.classList = [];
            if (obj.type == 1) {
                this.classList.push(obj)
            }

            this.searchForm.levelIds = obj.childrenIds ? obj.childrenIds.toString() : ''
            this.currentTreeNodeData = obj
            this.searchForm.nick = ''
            this.searchForm.studentNo = ''
            this.getData(this.searchForm)
        },

        // 选择班级回调
        filterClass(ids) {
            this.classList = []
            this.classList = this.classList.concat(ids)
            console.log("id", this.classList)
        },

        // 选择其他班级
        handleSelectOtherClass() {
            this.popup.selectClass = true
        },

        // 添加家长
        handleSaveAdmin(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    console.log("this.form", this.form)
                }
            });
        },

        handleCancel() {
            this.isShowParent = false
            this.isShowTable = true
            this.students = []
            this.form.name = ''
            this.form.id = ''
            this.form.type = 0
            this.form.parents.map(v => {
                v.parent = ''
                v.select = ''
            })
            this.form.parents = [{
                select: 0
            }]
        },

        // 选择班级弹窗
        handleAddClass() {
            this.popup.selectClass = true
        },

        // 删除tag
        handleClose(tag) {
            this.classList.splice(this.classList.indexOf(tag), 1)
        },

        handleDelLine(item) {
            if (this.form.parents.length !== 1)
                this.form.parents.splice(this.form.parents.indexOf(item), 1)
        },
        upLoadSuccess() {
            console.log('上传成功!!!')
            this.popup.studentBatchPopup = false
            this.getData(this.searchForm)
        },

        // 查看图片
        viewInfoDetail(row) {
            row.studentFacePicUrl
                ? this.$imgView([row.studentFacePicUrl], 0)
                : this.$imgView(['https://iconfont.alicdn.com/t/899dc690-1e58-46da-b0e1-cae72b1cdfba.png'], 0)
        },

        // 导出excel
        handleExportExcel() {
            let arr = ['schoolName']
            let tHeader = []
            let filterVal = []

            let cloneData = this.$u.deepClone(this.data)
            cloneData = cloneData.map((v) => {
                v.type = v.type == 0 ? '走读生' : '住宿生'
                v.gender = v.gender ? '男' : '女'
                return v
            })

            console.log("cloneData", cloneData)
            this.option.column.forEach((v) => {
                if (v.prop && !arr.includes(v.prop)) {
                    tHeader.push(v.label)
                    filterVal.push(v.prop)
                }
            })
            import('admin/vendor/Export2Excel').then((excel) => {
                const list = cloneData
                const data = this.formatJson(filterVal, list)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: '学生管理',
                    autoWidth: true,
                    bookType: 'xlsx',
                })
            })
        },

        formatJson(filterVal, jsonData) {
            return jsonData.map((v) =>
                filterVal.map((j) => {
                    if (j === 'timestamp') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                })
            )
        },
        // 导入学生
        importStudentNumber() {
            if (this.currentTreeNodeData === null) {
                return this.$message.error('请选择班级!!!')
            }

            if (this.currentTreeNodeData.type !== 1) {
                return this.$message.error('请具体选择到班级!!!')
            }

            this.popup.studentBatchPopup = true
        },

        // 海康学生授权
        authorizationStudent() {
            if (this.currentTreeNodeData === null) {
                return this.$message.error('请选择班级!!!')
            }

            if (this.currentTreeNodeData.type !== 1) {
                return this.$message.error('请具体选择到班级!!!')
            }

            this.popup.authorizationStudentPopup = true
        },
        // 同步数据
        async updateDataSynchronize() {
            this.loading = true
            const {code, data} = await this.$api.schoolConfig.studentList.updateDataSynchronize({schoolId: this.searchForm.schoolId})
            if (code === 200) {
                this.$notify({
                    message: '同步成功',
                    type: 'success',
                    duration: 2000,
                })
                this.errorData = data
                if (this.errorData.length > 0) {
                    this.showErrorData = true
                }
                await this.getData(this.searchForm)
            }
            this.loading = false
        },

        // 同步企业微信家长信息
        async handleQyDataSync(schoolId, id) {
            this.loading = true
            const {code} = await this.$api.schoolConfig.studentList.qyDataSync({
                schoolId,
                id,
            })
            if (code === 200) {
                this.$notify({
                    message: '同步成功',
                    type: 'success', //success, warning, info, error
                    duration: 2000,
                })
                await this.getData(this.searchForm)
            }
            this.loading = false
        },

        // 修改门禁消息状态
        async handlePutSendAccessMessage(row) {
            const {code} = await this.$api.schoolConfig.studentList.putAccessMessageAuthorize({
                accessControl: row.isSendAccessMessage,
                id: row.id,
                schoolId: row.schoolId,
            })
            if (code === 200) {
                this.$notify({
                    message: '更改成功',
                    type: 'success', //success, warning, info, error
                    duration: 2000,
                })
                return
            }
            //失败关闭
            row.isSendAccessMessage = false
        },

        // 删除行
        async handleRowDel(row) {
            let that = this
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    let {code} = await that.$api.schoolConfig.studentList.removeStudentInfo({id: row.id})
                    if (code === 200) {
                        that.$notify({
                            title: '提示',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000,
                        })
                        that.getData(that.searchForm)
                    }
                    done()
                })
                .catch(() => {
                })
        },

        // 编辑
        async handleRowUpdate(form, index, done, loading) {
            this.$refs.crud.validate(async (valid) => {
                if (valid) {
                    let {code, msg} = await this.$api.schoolConfig.studentList.updateStudentNo({
                        id: form.id,
                        studentNo: form.studentNo,
                        studentName: form.nick,
                        idCard: form.idCard,
                        type: form.type,
                    })
                    if (code === 200) {
                        this.$message.success('修改成功！' || msg)
                        this.getData(this.searchForm)
                    }
                    done()
                }
            })
        },

        // 查看家长列表
        async handleViewParents(row) {
            let {code, data} = await this.$api.schoolConfig.studentList.getStudentParentList({
                schoolId: this.searchForm.schoolId,
                studentId: row.id,
            })
            if (code === 200) {
                this.currentRow = row
                this.currentRow.parentList = data
                this.popup.parentListPopup = true
            }
        },

        handleEdit(row) {
            this.$refs.crud.rowEdit(row)
        },

        // 恢复
        async handleRestore(row) {
            this.$confirm('是否执行恢复操作, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',//success / info / warning / error
            }).then(async () => {
                const {code, data, msg} = await this.$api.schoolConfig.studentList.dataSynchronize({id: row.id, schoolId: this.searchForm.schoolId})
                if (code === 200) {
                    if (data && data.length === 0) {
                        this.$message({
                            showClose: true,
                            message: '恢复成功',
                            type: 'success',//success / info / warning / error
                        });
                    } else {
                        this.errorData = data;
                        this.showErrorData = true;
                        this.dialogTitle = '无法恢复的家长手机号'
                    }

                    this.getData(this.searchForm)
                }
            }).catch(() => {

            });

        },
        handleSendNotice() {
            this.popup.sendNotice = true
        },

        handleAddParent() {
            this.isShowTable = false
            this.isShowParent = true
        },

        // 发送当前行的通知
        handleSendCurrentNotice(row) {
            this.studentData = []
            let data = JSON.parse(JSON.stringify(row))
            data.label = data.nick;
            this.studentData.push(data)
            this.popup.sendNotice = true
        },

        // 学生信息同步
        async handleInfoSync(schoolId, id) {
            let {code, msg} = await this.$api.schoolConfig.studentList.studentInfoSync({id, schoolId})
            if (code === 200) {
                this.$notify({
                    title: '提示',
                    message: '同步成功',
                    type: 'success',
                    duration: 2000,
                })
                that.getData(that.searchForm)
            }
        },
        // 错误提示
        error(err) {
            this.$message.success('请查看控制台')
            console.log(err)
        },

        //获取人脸头像
        getFaceImg(faceImg) {
            this.faceImg = faceImg
        },
    },
}
</script>

<style lang="scss" scoped>
.studentList {
    height: 100%;
    //overflow: hidden;
    .item-box {
        margin-bottom: 15px;
    }

    .addParentForm {
        /deep/ .el-select .el-input {
            width: 100px;
        }

        .input-with-select .el-input-group__prepend {
            background-color: #fff;
        }
    }

}
</style>
